package cn.itcast.com.queue;

import java.util.NoSuchElementException;

/*
入队 队尾添加元素
出队 对头删除元素
判空
长度
 */
public class MyQueue<E> {
    //默认的长度
    private static final Integer DEFAULT_CAPACITY = 10;
    //最大长度
    private static final Integer MAX_CAPACITY = Integer.MAX_VALUE -8;
    //初始用的数组
    private Object[] list;

    private Integer head;
    private Integer end;
    private Integer size;

    public MyQueue() {
        this.list = new Object[DEFAULT_CAPACITY];
    }

    public MyQueue(int initialCapacity) {
        if (initialCapacity < 0 || initialCapacity > MAX_CAPACITY){
            throw new IllegalArgumentException("error");
        }
        this.list = new Object[initialCapacity];
    }
    public E peek(){
        return (E)list[head];
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public Integer getSize() {
        return size;
    }

    public E dequeue(){
        if (isEmpty()){
            throw new NoSuchElementException();
        }
        E value = (E)list[head];
        head = (head + 1) % list.length;
        size--;
        return value;
    }

    public void enqueue(E e){
        if (size == list.length){
            //满了，扩容
            int newCapacity = Capacity();
            grow(newCapacity);


        }else {
            end  = (end + 1) % list.length;
            list[end] = e;
            size++;
        }
    }

    private void grow(int newCapacity) {
        Object[] newList = new Object[newCapacity];
        //根据旧的数组长度来遍历
        for (int i = 0; i < size; i++) {
            int tag = (head + i) % list.length;
            newList[i] = list[tag];
        }
        //重新赋值给list
        list = newList;
        head = 0;
        end = size -1;
    }

    private int Capacity() {
        if (size >= MAX_CAPACITY){
            throw new RuntimeException();
        }
        int newCapacity = size + (size >> 1);
        if (newCapacity <= 0 || newCapacity > MAX_CAPACITY){
            return MAX_CAPACITY;
        }else {
            return newCapacity;
        }
    }


}
